package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class HandlerThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        System.out.println(this + " creating new thread");
        Thread t = new Thread(r);
        System.out.println("created " + t);
        Thread.UncaughtExceptionHandler handler = new MyUncaughtExceptionHandler();
        System.out.println("created " + handler);
        t.setUncaughtExceptionHandler(handler);
        return t;
    }
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("caught : " + e);
    }
}

class ExceptionThread implements Runnable {
    @Override
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println(t);
        System.out.println(t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

/**
 * Thread.UncaughtExceptionHandler
 *
 * 2018年 09月 26日 星期三
 * @author fireway
 */
public class CaptureUncaughtEception {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
        exec.execute(new ExceptionThread());
        exec.shutdown();
    }
}
